const Router = require("koa-router");
const api=require("../database");

const router = new Router({
    prefix:"/cors"
});
router.get("/test",async function(ctx){
    ctx.body="/cors/test请求成功";
});

router.get("/jsonp",async function(ctx){
  

    let funName=ctx.query.callback;//show
    let obj={
        a:Math.random(),
        b:200,
        arr:[100,200,300,400]
    };
    let str=JSON.stringify(obj);
    ctx.body=funName+"("+str+")";
   
});

const originList=[
    "http://127.0.0.1:5500",
    "http://localhost:5500"
];
router.get("/corsArea",async function(ctx){

    // console.log(ctx.headers.origin);//获取请求头
    // console.log(ctx.headers["origin"]);
    //设置允许跨域的请求
    // koa通过ctx.set("响应头名",响应头值) 进行响应头设置
    // ctx.set("Access-Control-Allow-Origin","*");
    // ctx.set("Access-Control-Allow-Origin","http://127.0.0.1:5500");
    // ctx.set("Access-Control-Allow-Origin","http://127.0.0.1:5500");

    let origin=ctx.headers.origin;
    if(originList.includes(origin)){
        ctx.set("Access-Control-Allow-Origin",origin);
    }


    ctx.body="hello，你终于拿到我的数据了";
});


module.exports={
    "corsRouter": router
};